'use client';

import { useState, useEffect, useMemo } from 'react';
import styled from 'styled-components';
import { DroneInfo, TrajectoryData, TrajectoryModalProps } from './types';
import dynamic from 'next/dynamic';

// 动态导入Cesium组件，避免SSR问题
const TrajectoryViewer = dynamic(() => import('./TrajectoryViewer'), { 
  ssr: false, 
  loading: () => (
    <div className="w-full h-full flex items-center justify-center">
      <div className="text-blue-300">加载地图组件中...</div>
    </div>
  ) 
});

// 弹窗背景遮罩
const ModalOverlay = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.7);
  backdrop-filter: blur(3px);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
`;

// 弹窗容器
const ModalContainer = styled.div`
  width: 80%;
  height: 80%;
  background-color: rgba(0, 21, 41, 0.9);
  border: 2px solid rgba(24, 144, 255, 0.7);
  border-radius: 8px;
  box-shadow: 0 0 30px rgba(24, 144, 255, 0.3);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
`;

// 弹窗标题栏
const ModalHeader = styled.div`
  padding: 15px 20px;
  background-color: rgba(24, 144, 255, 0.3);
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(24, 144, 255, 0.5);
`;

// 弹窗标题
const ModalTitle = styled.h2`
  color: white;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  display: flex;
  align-items: center;
  
  &::before {
    content: '';
    width: 20px;
    height: 20px;
    background-image: url('/images/dashboard/icons/history-icon.svg');
    background-size: contain;
    background-repeat: no-repeat;
    margin-right: 10px;
    display: inline-block;
  }
`;

// 关闭按钮
const CloseButton = styled.button`
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.7);
  font-size: 24px;
  cursor: pointer;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s;
  
  &:hover {
    background-color: rgba(255, 255, 255, 0.1);
    color: white;
  }
`;

// 弹窗内容区
const ModalContent = styled.div`
  display: flex;
  flex: 1;
  overflow: hidden;
`;

// 左侧控制面板
const ControlPanel = styled.div`
  width: 30%;
  background-color: rgba(0, 15, 30, 0.7);
  border-right: 1px solid rgba(24, 144, 255, 0.3);
  padding: 15px;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.1);
  }
  
  &::-webkit-scrollbar-thumb {
    background: rgba(24, 144, 255, 0.3);
    border-radius: 3px;
  }
`;

// 右侧地图容器
const MapPanel = styled.div`
  width: 70%;
  position: relative;
`;

// 分段标题
const SectionTitle = styled.h3`
  color: #a0cfff;
  font-size: 14px;
  font-weight: 500;
  margin: 15px 0 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid rgba(24, 144, 255, 0.3);
  
  &:first-child {
    margin-top: 0;
  }
`;

// 天数选择器
const DaysSelector = styled.div`
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
`;

// 天数按钮
const DayButton = styled.button<{ active: boolean }>`
  flex: 1;
  padding: 6px 0;
  background-color: ${props => props.active ? 'rgba(24, 144, 255, 0.5)' : 'rgba(24, 144, 255, 0.2)'};
  color: white;
  border: 1px solid rgba(24, 144, 255, 0.5);
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.2s;
  
  &:hover {
    background-color: rgba(24, 144, 255, 0.4);
  }
`;

// 列表容器
const ListContainer = styled.div`
  margin-bottom: 15px;
  flex: 1;
  overflow-y: auto;
  
  &::-webkit-scrollbar {
    width: 5px;
  }
  
  &::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.1);
  }
  
  &::-webkit-scrollbar-thumb {
    background: rgba(24, 144, 255, 0.3);
    border-radius: 3px;
  }
`;

// 列表项
const ListItem = styled.div<{ active: boolean }>`
  padding: 10px;
  background-color: ${props => props.active ? 'rgba(24, 144, 255, 0.3)' : 'transparent'};
  border-left: 3px solid ${props => props.active ? '#1890ff' : 'transparent'};
  margin-bottom: 5px;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    background-color: ${props => props.active ? 'rgba(24, 144, 255, 0.3)' : 'rgba(24, 144, 255, 0.1)'};
  }
`;

// 无人机项标题
const DroneItemTitle = styled.div`
  color: white;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 3px;
`;

// 无人机项描述
const DroneItemDesc = styled.div`
  color: #a0cfff;
  font-size: 12px;
  display: flex;
  justify-content: space-between;
`;

// 日期项
const DateItem = styled.div<{ active: boolean }>`
  padding: 8px 10px;
  background-color: ${props => props.active ? 'rgba(24, 144, 255, 0.3)' : 'transparent'};
  border-left: 3px solid ${props => props.active ? '#1890ff' : 'transparent'};
  margin-bottom: 4px;
  cursor: pointer;
  color: ${props => props.active ? 'white' : '#a0cfff'};
  font-size: 13px;
  transition: all 0.2s;
  
  &:hover {
    background-color: ${props => props.active ? 'rgba(24, 144, 255, 0.3)' : 'rgba(24, 144, 255, 0.1)'};
  }
`;

// 加载中组件
const Loading = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  color: #a0cfff;
  font-size: 14px;
`;

// 空数据提示
const EmptyData = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  color: #a0cfff;
  font-size: 14px;
  opacity: 0.6;
`;

export default function TrajectoryModal({ onClose }: TrajectoryModalProps) {
  const [daysFilter, setDaysFilter] = useState(7);
  const [droneList, setDroneList] = useState<DroneInfo[]>([]);
  const [dateList, setDateList] = useState<string[]>([]);
  const [selectedDrone, setSelectedDrone] = useState<string | null>(null);
  const [selectedSensorId, setSelectedSensorId] = useState<string | null>(null);
  const [selectedDate, setSelectedDate] = useState<string | null>(null);
  const [trajectoryData, setTrajectoryData] = useState<TrajectoryData | null>(null);
  const [loading, setLoading] = useState({
    drones: true,
    dates: false,
    trajectory: false
  });

  // 获取无人机列表
  useEffect(() => {
    const fetchDroneList = async () => {
      setLoading(prev => ({ ...prev, drones: true }));
      try {
        const response = await fetch('http://113.45.136.1:5100/api/drone/list');
        const data = await response.json();
        
        if (data.code === 0) {
          // 直接使用API返回的列表，包含sensor_id和combined_id
          setDroneList(data.data);
        } else {
          console.error('获取无人机列表失败:', data.message);
        }
      } catch (error) {
        console.error('获取无人机列表出错:', error);
      } finally {
        setLoading(prev => ({ ...prev, drones: false }));
      }
    };
    
    fetchDroneList();
  }, []);

  // 按无人机ID对列表进行分组
  const groupedDrones = useMemo(() => {
    const grouped: { [key: string]: { 
      gui_id: string; 
      model: string; 
      sensors: { 
        sensor_id: string; 
        combined_id: string; 
        detection_count: number; 
        last_seen: string;
      }[] 
    }} = {};
    
    droneList.forEach(drone => {
      if (!grouped[drone.gui_id]) {
        grouped[drone.gui_id] = {
          gui_id: drone.gui_id,
          model: drone.model,
          sensors: []
        };
      }
      
      grouped[drone.gui_id].sensors.push({
        sensor_id: drone.sensor_id,
        combined_id: drone.combined_id,
        detection_count: drone.detection_count,
        last_seen: drone.last_seen
      });
    });
    
    return grouped;
  }, [droneList]);

  // 获取日期列表
  useEffect(() => {
    if (!selectedDrone || !selectedSensorId) return;
    
    const fetchDateList = async () => {
      setLoading(prev => ({ ...prev, dates: true }));
      try {
        const response = await fetch(`http://113.45.136.1:5100/api/drone/dates?gui_id=${selectedDrone}&sensor_id=${selectedSensorId}`);
        const data = await response.json();
        
        if (data.code === 0) {
          setDateList(data.data);
        } else {
          console.error('获取日期列表失败:', data.message);
        }
      } catch (error) {
        console.error('获取日期列表出错:', error);
      } finally {
        setLoading(prev => ({ ...prev, dates: false }));
      }
    };
    
    fetchDateList();
  }, [selectedDrone, selectedSensorId]);

  // 获取轨迹数据
  useEffect(() => {
    if (!selectedDrone || !selectedSensorId || !selectedDate) return;
    
    const fetchTrajectoryData = async () => {
      setLoading(prev => ({ ...prev, trajectory: true }));
      try {
        const response = await fetch(`http://113.45.136.1:5100/api/drone/trajectory?gui_id=${selectedDrone}&sensor_id=${selectedSensorId}&days=${daysFilter}`);
        const data = await response.json();
        
        if (data.code === 0) {
          console.log("收到轨迹数据:", data);
          const formattedData: TrajectoryData = {};
          
          // 处理新API结构
          const combinedId = `${selectedDrone}_${selectedSensorId}`;
          if (data.data && data.data[combinedId]) {
            formattedData[combinedId] = {
              gui_id: selectedDrone,
              sensor_id: selectedSensorId,
              dates: {}
            };
            
            // 处理日期数据
            if (data.data[combinedId].dates) {
              Object.keys(data.data[combinedId].dates).forEach(date => {
                const trajectoryPoints = data.data[combinedId].dates[date].map((point: {
                  drone_height?: number;
                  drone_gps_lat?: number;
                  drone_gps_lng?: number;
                  drone_distance?: number;
                  sensor_id?: string;
                  model?: string;
                  created_at?: string;
                }) => ({
                  drone_height: point.drone_height || 0,
                  drone_gps_lat: point.drone_gps_lat || 0,
                  drone_gps_lng: point.drone_gps_lng || 0,
                  drone_distance: point.drone_distance || 0,
                  sensor_id: point.sensor_id || '',
                  model: point.model || '',
                  created_at: point.created_at || ''
                }));
                
                formattedData[combinedId].dates[date] = trajectoryPoints;
              });
            }
          }
          
          console.log('处理后的轨迹数据:', formattedData);
          setTrajectoryData(formattedData);
        } else {
          console.error('获取轨迹数据失败:', data.message);
        }
      } catch (error) {
        console.error('获取轨迹数据出错:', error);
      } finally {
        setLoading(prev => ({ ...prev, trajectory: false }));
      }
    };
    
    fetchTrajectoryData();
  }, [selectedDrone, selectedSensorId, selectedDate, daysFilter]);

  // 处理选择无人机和传感器
  const handleSelectDroneSensor = (guiId: string, sensorId: string) => {
    setSelectedDrone(guiId);
    setSelectedSensorId(sensorId);
    setSelectedDate(null);
  };

  // 处理选择日期
  const handleSelectDate = (date: string) => {
    console.log('选择的日期:', date);
    setSelectedDate(date);
  };

  // 处理更改天数筛选
  const handleDaysChange = (days: number) => {
    setDaysFilter(days);
  };

  return (
    <ModalOverlay onClick={(e) => e.stopPropagation()}>
      <ModalContainer>
        <ModalHeader>
          <ModalTitle>历史轨迹监测</ModalTitle>
          <CloseButton onClick={onClose}>×</CloseButton>
        </ModalHeader>
        
        <ModalContent>
          <ControlPanel>
            <SectionTitle>查询天数</SectionTitle>
            <DaysSelector>
              <DayButton 
                active={daysFilter === 7} 
                onClick={() => handleDaysChange(7)}
              >
                近7天
              </DayButton>
              <DayButton 
                active={daysFilter === 15} 
                onClick={() => handleDaysChange(15)}
              >
                近15天
              </DayButton>
              <DayButton 
                active={daysFilter === 30} 
                onClick={() => handleDaysChange(30)}
              >
                近30天
              </DayButton>
            </DaysSelector>
            
            <SectionTitle>无人机列表</SectionTitle>
            <ListContainer>
              {loading.drones ? (
                <Loading>加载中...</Loading>
              ) : Object.keys(groupedDrones).length === 0 ? (
                <EmptyData>暂无无人机数据</EmptyData>
              ) : (
                Object.values(groupedDrones).map(droneGroup => (
                  <div key={droneGroup.gui_id}>
                    <DroneItemTitle>{droneGroup.model} ({droneGroup.gui_id})</DroneItemTitle>
                    {droneGroup.sensors.map(sensor => (
                      <ListItem 
                        key={sensor.combined_id}
                        active={selectedDrone === droneGroup.gui_id && selectedSensorId === sensor.sensor_id}
                        onClick={() => handleSelectDroneSensor(droneGroup.gui_id, sensor.sensor_id)}
                      >
                        <DroneItemDesc>
                          <span>传感器: {sensor.sensor_id}</span>
                          <span>检测: {sensor.detection_count}次</span>
                        </DroneItemDesc>
                      </ListItem>
                    ))}
                  </div>
                ))
              )}
            </ListContainer>
            
            <SectionTitle>历史日期</SectionTitle>
            <ListContainer>
              {!selectedDrone || !selectedSensorId ? (
                <EmptyData>请先选择无人机和传感器</EmptyData>
              ) : loading.dates ? (
                <Loading>加载中...</Loading>
              ) : dateList.length === 0 ? (
                <EmptyData>暂无历史数据</EmptyData>
              ) : (
                dateList.map(date => (
                  <DateItem 
                    key={date}
                    active={selectedDate === date}
                    onClick={() => handleSelectDate(date)}
                  >
                    {date}
                  </DateItem>
                ))
              )}
            </ListContainer>
          </ControlPanel>
          
          <MapPanel>
            {loading.trajectory ? (
              <div className="w-full h-full flex items-center justify-center">
                <div className="text-blue-300">加载轨迹数据中...</div>
              </div>
            ) : !selectedDrone || !selectedSensorId || !selectedDate ? (
              <div className="w-full h-full flex items-center justify-center">
                <div className="text-blue-300 text-center">
                  <div>请选择无人机、传感器和日期</div>
                  <div className="text-xs mt-2 opacity-70">在左侧面板选择需要查看的无人机、传感器和日期</div>
                </div>
              </div>
            ) : (
              <div style={{ width: '100%', height: '100%' }}>
                <TrajectoryViewer 
                  trajectoryData={trajectoryData} 
                  droneId={selectedDrone}
                  sensorId={selectedSensorId}
                  date={selectedDate}
                  isLoading={loading.trajectory}
                />
              </div>
            )}
          </MapPanel>
        </ModalContent>
      </ModalContainer>
    </ModalOverlay>
  );
} 